package com.zhangkunhao.notes.service;

import com.zhangkunhao.notes.dao.PursueListDao;

import com.zhangkunhao.notes.entity.Do.PursueList;
import com.zhangkunhao.notes.entity.Do.Question;
import com.zhangkunhao.notes.entity.Do.User;
import com.zhangkunhao.notes.entity.bo.Message;
import com.zhangkunhao.notes.entity.bo.PageBean;
import com.zhangkunhao.notes.service.impl.PursueListService;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 关注列表接口的实现类
 *
 * @author 20642
 */
public class PursueListServiceImpl implements PursueListService {
    private UserServiceImpl userService = new UserServiceImpl();
    private QuestionServiceImpl questionService = new QuestionServiceImpl();

    @Override
    public List<PursueList> selectAll() {
        return PursueListDao.getInstance().findAll();
    }

    @Override
    public void insert(PursueList pursueList) throws Exception {
        PursueListDao.getInstance().insert(pursueList);
    }

    @Override
    public int delete(int id) throws SQLException {
        return PursueListDao.getInstance().delete(id);
    }

    @Override
    public int update(PursueList pursueList, String... params) throws Exception {
        return PursueListDao.getInstance().update(pursueList);
    }

    /**
     * 查询我还没有关注的用户
     *
     * @param userId：
     * @return PageBean<User>
     */
    public PageBean<User> listPursuingUsers(int userId) {
        // 调用dao查询关注的用户的id
        List<Integer> pursuedUserIds = this.selectAll().stream()
                .filter(pursueList -> pursueList.getPursuingId().equals(userId))
                .map(PursueList::getPursuedId)
                .collect(Collectors.toList());

        // 调用dao查询除了自己之外的用户
        List<User> userList = userService.selectAll()
                .stream()
                .filter(user1 -> (!user1.getId().equals(userId)))
                .collect(Collectors.toList());

        // 迭代器,过滤已经关注的用户
        Iterator<User> it = userList.iterator();
        while (it.hasNext()) {
            User user = it.next();
            for (Integer pursuedId : pursuedUserIds) {
                if (user.getId().equals(pursuedId)) {
                    //不能是userList.remove(user)
                    it.remove();
                    break;
                }
            }
        }

        //返回数据
        return new PageBean<>(userList.size(), userList);
    }

    /**
     * 显示我关注的用户
     *
     * @param userId：
     * @return PageBean<User>
     */
    public PageBean<User> listMyPursueUsers(int userId) {
        //查询已经关注的用户的id
        List<Integer> myPursueUserIds = this.selectAll().stream()
                .filter(pursueList -> pursueList.getPursuingId().equals(userId))
                .map(PursueList::getPursuedId)
                .collect(Collectors.toList());

        // 调用dao查询除了自己之外的用户
        List<User> userList = userService.selectAll()
                .stream()
                .filter(user1 -> (!user1.getId().equals(userId)))
                .collect(Collectors.toList());

        // 迭代器，过滤掉没有关注的用户
        Iterator<User> it = userList.iterator();

        //是否在我的用户关注名单内
        boolean isPursueList;

        //过滤
        while (it.hasNext()) {
            isPursueList = false;
            User user = it.next();
            for (Integer myPursueUserId : myPursueUserIds) {
                if (user.getId().equals(myPursueUserId)) {
                    isPursueList = true;
                    break;
                }
            }
            if (!isPursueList) {
                //不能是userList.remove(user)
                it.remove();
            }
        }
        //返回数据
        return new PageBean<>(userList.size(), userList);
    }

    /**
     * 查询共同关注的用户列表
     *
     * @param userId：
     * @param oppositeUserId：我关注的用户的id
     * @return PageBean<User>
     */
    public PageBean<User> listCommonPursueUsers(int userId, int oppositeUserId) {
        //查询我已经关注的用户的id
        List<Integer> myPursueUserIds = this.selectAll().stream()
                .filter(pursueList -> pursueList.getPursuingId().equals(userId))
                .map(PursueList::getPursuedId)
                .collect(Collectors.toList());

        //查询对方已经关注的用户的id
        List<Integer> oppositePursueUserIds = this.selectAll().stream()
                .filter(pursueList -> pursueList.getPursuingId().equals(oppositeUserId))
                .map(PursueList::getPursuedId)
                .collect(Collectors.toList());

        //取两个集合的交集
        ArrayList<Integer> newList = new ArrayList<>(myPursueUserIds);
        newList.retainAll(oppositePursueUserIds);

        // 调用dao查询除了自己和对方之外的用户
        List<User> userList = userService.selectAll().stream()
                .filter(user1 -> (!user1.getId().equals(userId)) && (!user1.getId().equals(oppositeUserId)))
                .collect(Collectors.toList());

        // 迭代器，过滤掉任何一方没有关注的用户
        Iterator<User> it = userList.iterator();

        //是否在双方共同的关注名单内
        boolean isPursueList;

        //过滤
        while (it.hasNext()) {
            isPursueList = false;
            User user = it.next();
            for (Integer commonPursueUserId : newList) {
                if (user.getId().equals(commonPursueUserId)) {
                    isPursueList = true;
                    break;
                }
            }
            if (!isPursueList) {
                //不能是userList.remove(user)
                it.remove();
            }
        }

        //返回数据
        return new PageBean<>(userList.size(), userList);
    }

    /**
     * 关注用户
     *
     * @param userId：
     * @param pursueUserId：被关注的用户的id
     * @return Message<PursueList>
     * @throws Exception:
     */
    public Message<PursueList> pursueUser(int userId, int pursueUserId) throws Exception {
        //初始化
        Message<PursueList> pursueListMessage = new Message<>(null, "关注该用户失败", 0);

        PursueList pursueList = new PursueList(null, userId, pursueUserId);

        //调用dao
        this.insert(pursueList);

        //提供判断
        PursueList pursueList2 = this.selectAll()
                .stream()
                .filter(pursueList3 -> pursueList3.getPursuingId().equals(userId) && pursueList3.getPursuedId().equals(pursueUserId))
                .collect(Collectors.toList()).get(0);

        //成功
        if (pursueList2 != null) {
            pursueListMessage.setResult("关注该用户成功");
            pursueListMessage.setStatus(1);
            pursueListMessage.setT(pursueList2);
        }

        //更新被关注者的关注数量
        User pursuedUser = userService.selectAll().stream()
                .filter(user1 -> user1.getId().equals(pursueUserId))
                .collect(Collectors.toList()).get(0);
        pursuedUser.setFansCount(pursuedUser.getFansCount() + 1);

        //调用dao
        userService.update(pursuedUser);

        //返回数据
        return pursueListMessage;
    }

    /**
     * 取消关注用户
     *
     * @param userId：
     * @param cancelPursueUserId：被取消关注的用户的id
     * @return Message<PursueList>
     * @throws Exception：
     */
    public Message<PursueList> cancelPursueUser(int userId, int cancelPursueUserId) throws Exception {

        //初始化
        Message<PursueList> pursueListMessage = new Message<>(null, "取消关注失败", 0);

        //调用dao
        PursueList pursueList = this.selectAll().stream()
                .filter(pursueList1 -> pursueList1.getPursuingId().equals(userId) && pursueList1.getPursuedId().equals(cancelPursueUserId))
                .collect(Collectors.toList()).get(0);

        int delete = this.delete(pursueList.getId());

        //成功
        if (delete > 0) {
            pursueListMessage.setResult("取消关注成功");
            pursueListMessage.setStatus(1);
        }
        //更新粉丝关注数量
        User cancelPursueUser = userService.selectAll().stream()
                .filter(user1 -> user1.getId().equals(cancelPursueUserId))
                .collect(Collectors.toList()).get(0);
        cancelPursueUser.setFansCount(cancelPursueUser.getFansCount() - 1);

        //调用dao
        userService.update(cancelPursueUser);
        //返回数据
        return pursueListMessage;
    }

    /**
     * 展示我关注的用户发表的问题
     *
     * @param userId：
     * @return PageBean<Question>
     */
    public PageBean<Question> showMyPursueUserQuestions(int userId) {
        //查询我已经关注的用户的id
        List<Integer> myPursueUserIds = this.selectAll().stream()
                .filter(pursueList -> pursueList.getPursuingId().equals(userId))
                .map(PursueList::getPursuedId)
                .collect(Collectors.toList());
        //没有关注过用户
        if (myPursueUserIds.isEmpty()) {
            return new PageBean<>(-1, null);
        }
        //调用dao
        List<Question> questions = questionService.selectAll().stream()
                .filter(question -> question.getCheckStatus() == 1 && question.getReportStatus() == 1)
                .collect(Collectors.toList());

        // 迭代器，过滤掉不是我关注的用户发表的问题
        Iterator<Question> it = questions.iterator();

        //是否该问题是我关注的用户发表的
        boolean isPursueList;

        while (it.hasNext()) {
            isPursueList = false;
            Question question = it.next();
            for (Integer myPursueUserId : myPursueUserIds) {
                if (question.getPublishUserId().equals(myPursueUserId)) {
                    isPursueList = true;
                    break;
                }
            }
            if (!isPursueList) {
                it.remove();
            }
        }

        //返回数据
        return new PageBean<>(questions.size(), questions);
    }

    /**
     * 将我关注的用户发表的问题按点赞数量排序
     *
     * @param userId：
     * @return PageBean<Question>
     */
    public PageBean<Question> rankByLikesCount(int userId) {
        //查询我已经关注的用户的id
        List<Integer> myPursueUserIds = this.selectAll().stream()
                .filter(pursueList -> pursueList.getPursuingId().equals(userId))
                .map(PursueList::getPursuedId)
                .collect(Collectors.toList());
        //没有关注过用户
        if (myPursueUserIds.isEmpty()) {
            return new PageBean<>(-1, null);
        }

        //调用dao
        List<Question> questions = questionService.selectAll().stream()
                .filter(question -> question.getCheckStatus() == 1 && question.getReportStatus() == 1)
                .collect(Collectors.toList());

        // 迭代器过滤
        Iterator<Question> it = questions.iterator();

        //是否问题是我关注的用户发表的
        boolean isPursueList;

        while (it.hasNext()) {
            isPursueList = false;
            Question question = it.next();
            for (Integer myPursueUserId : myPursueUserIds) {
                if (question.getPublishUserId().equals(myPursueUserId)) {
                    isPursueList = true;
                    break;
                }
            }
            if (!isPursueList) {
                it.remove();
            }
        }
        //返回数据
        if (!questions.isEmpty()) {
            List<Question> sortedQuestion = questions.stream().sorted((o1, o2) -> o2.getLikeCount() - o1.getLikeCount()).collect(Collectors.toList());
            return new PageBean<>(sortedQuestion.size(), sortedQuestion);
        } else {
            return new PageBean<>(0, null);
        }
    }

    /**
     * 将我关注的用户发表的问题按发布时间排序
     *
     * @param userId：
     * @return PageBean<Question>
     */
    public PageBean<Question> rankByLaunchTime(int userId) {
        //查询我已经关注的用户的id
        List<Integer> myPursueUserIds = this.selectAll().stream()
                .filter(pursueList -> pursueList.getPursuingId().equals(userId))
                .map(PursueList::getPursuedId)
                .collect(Collectors.toList());
        //没有关注过用户
        if (myPursueUserIds.isEmpty()) {
            return new PageBean<>(-1, null);
        }

        //调用dao
        List<Question> questions = questionService.selectAll().stream()
                .filter(question -> question.getCheckStatus() == 1 && question.getReportStatus() == 1)
                .collect(Collectors.toList());
        // 迭代器过滤
        Iterator<Question> it = questions.iterator();

        //是否问题是我关注的用户发表的
        boolean isPursueList;

        while (it.hasNext()) {
            isPursueList = false;
            Question question = it.next();
            for (Integer myPursueUserId : myPursueUserIds) {
                if (question.getPublishUserId().equals(myPursueUserId)) {
                    isPursueList = true;
                    break;
                }
            }
            if (!isPursueList) {
                it.remove();
            }
        }

        //返回数据
        if (!questions.isEmpty()) {
            List<Question> collect = questions.stream().sorted((o1, o2) -> o2.getLaunchTime().compareTo(o1.getLaunchTime())).collect(Collectors.toList());
            return new PageBean<>(collect.size(), collect);
        } else {
            return new PageBean<>(0, null);
        }
    }
}
